<template>
  <div>
    <draggable handle=".handle" v-model="localItems" @change="onDragChange">
      <div v-for="(item, index) in items" :key="index" style="display: flex;">
        <div class="form-group">
          <el-input
              :size="size"
              type="text"
              class="form-control"
              v-model="items[index].label"
              placeholder="请输入标签名(label)"/>
        </div>
        <div class="form-group">
          <el-input
              :size="size"
              type="text"
              class="form-control"
              v-model="items[index].value"
              placeholder="请输入值(value)"/>
        </div>
        <div class="form-group">
          <el-input
              :size="size"
              type="text"
              class="form-control"
              v-model="items[index].type"
              placeholder="ElementUI主题配色可选(optional)"/>
        </div>
        <div class="form-group">
          <el-button :size="size" type="danger" icon="el-icon-close" @click="removeItem(index)"></el-button>
        </div>
        <div class="form-group">
          <el-button :size="size" type="info" icon="el-icon-rank" class="handle"></el-button>
        </div>
      </div>
    </draggable>
    <el-button :size="size" type="primary" @click="addItem">添加</el-button>
  </div>
</template>

<script>
import draggable from "vuedraggable"

export default {
  name: "key-value",
  components: {
    draggable
  },
  props: {
    items: {
      type: Array,
      required: true,
      default: () => []
    },
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      localItems: [] // 子组件内部用于跟踪列表状态的数据属性
    };
  },
  watch: {
    // 当父组件传入的items变化时，更新子组件内的localItems
    items: {
      immediate: true,
      handler(newItems) {
        this.localItems = [...newItems]; // 使用展开运算符复制数组
      }
    }
  },
  methods: {
    addItem() {
      this.items.push({label: '', value: '', type: ''});
    },
    removeItem(index) {
      this.items.splice(index, 1);
    },
    onDragChange(event) {
      // event.oldIndex 和 event.newIndex 分别代表元素之前的索引和新的索引
      this.$emit("update:items", this.localItems);
      console.log("Drag ended:", event);
    }
  }
}
</script>

<style scoped>
.form-group {
  padding: 1px;
}

</style>